package com.lostsheep.service.impl;

import com.alibaba.fastjson.JSON;
import com.lostsheep.dto.CommonDTO;
import com.lostsheep.dto.UserDTO;
import com.lostsheep.rpc.UserRpc;
import com.lostsheep.service.UserService;
import com.lostsheep.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <b><code>UserServiceImpl</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 2024/7/6.
 *
 * @author dengzhen
 * @since spring-cloud-dubbo
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @DubboReference
    private UserRpc userRpc;

    @Override
    public UserVO getUser(Long id) {
        UserDTO user = userRpc.getUser(id);
        UserDTO optUserDTO = Optional.ofNullable(user).orElse(new UserDTO());
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(optUserDTO, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUsers() {
        log.info("rpc 接口请求......");
        CommonDTO<List<UserDTO>> commonDTO = userRpc.getUsers();
        log.info("rpc 接口响应: {}", JSON.toJSONString(commonDTO));
        List<UserDTO> optUserList = commonDTO.getData().stream()
                .map(user -> Optional.ofNullable(user).orElse(new UserDTO()))
                .collect(Collectors.toList());
        return optUserList.stream()
                .map(optUserDTO -> {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(optUserDTO, userVO);
                    return userVO;
                })
                .collect(Collectors.toList());
    }
}
